<?php

class URI {
	
	var $config;
	var $allowed = FALSE;
 	var $source;
 	var $class;
 	var $method = 'index';
 	var $cache = -1;
 	
 	/** 前置钩子 */
 	var $pre_hooks;
 	/** 后置钩子 */
 	var $post_hooks;
 	
	var $uri;
	var $url_this;
	var $params = array();
	
	function URI() {
		$this->config = get_config();
	}
	
	function parse() {
		// 获取协议头
		$http_protocol = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ) ? 'https://' : 'http://';
		$this->url_this = $http_protocol . $_SERVER ['HTTP_HOST'] . $_SERVER['PHP_SELF'];		
		if( $this->url_this == $this->config['base_url'] || $this->url_this == $this->config['base_url'] . $this->config['index_page']) {
			$this->uri = 'default';	
		}
		else {
			$this->uri = str_replace( $this->config['base_url'] . $this->config['index_page'] . '/', '', $this->url_this );
		}
		
		/** 导入URL映射 */
		require( ABSPATH . 'urls.php');
		
		foreach( $urls as $key => $value ) {
			$url_pattern = preg_replace('/<\w+>/e', '${1}', $key);
			$url_pattern = '/' . $url_pattern . '/';
			
			if( preg_match($url_pattern, $this->uri) ) {
				$this->get_url_params($key);
				
				$this->source = $value['src'];
				$this->class = $value['class'];
				
				if( isset( $value['func'] ) ) {
					$this->method = $value['func'];	
				}
				
				// 获取参数
				if( isset($value['params']) ) {
					$params_str = $value['params'];
					$params_array = explode(',', $params_str);
					foreach($params_array as $param) {
						$temp_array = explode('=', $param);
						$this->params[ $temp_array[0] ] = $temp_array[1];
					}
				}
				
				// 获取前置钩子列表
				if( isset( $value['pre'] ) ) {
					$this->pre_hooks = explode(',', $value['pre']);
				}
				
				// 获取后置钩子列表
				if( isset( $value['post'] ) ) {
					$this->post_hooks = explode(',', $value['post']);
				}
				
				// 获取缓存参数
				if( isset( $value['cache'] ) ) {
					$this->cache = $value['cache'];
				}
				
				$this->allowed = true;
				break;
			}
		}
		
		// 没有相匹配的URI，响应404页面
		if( ! $this->allowed ) {
			include(TATUPATH . 'errors/404.php');
			exit;
		}
	}
	
	/**
	 * 获取URL中定义的参数
	 * @param $pattern
	 * @return void
	 */
	function get_url_params($pattern) {	
		$pattern_array = preg_split('/\//', $pattern);
		$uri_array = preg_split('/\//', $this->uri);
		
		$i = 0;
		foreach($pattern_array as $pattern_segment) {
			if( preg_match('/<\w+>*+/', $pattern_segment, $param_array) ) {
				$param_key = substr($param_array[0], 1, strlen($param_array[0])-2);
				$this->params[$param_key] = $uri_array[$i];
			}
			$i++;
		}
	}
	
}



?>